package com.atkxp.sys.service.impl;

import com.atkxp.sys.entity.LoginUser;
import com.atkxp.sys.entity.Menu;
import com.atkxp.sys.entity.User;
import com.atkxp.sys.mapper.MenuMapper;
import com.atkxp.sys.mapper.UserMapper;
import com.atkxp.sys.service.IMenuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author longhunpomie
 * @declaration
 * @email 3314028177@qq.com
 * @create 2023/9/13-18:16
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);

        if(user == null) {
            throw new RuntimeException("用户不存在");
        }

//        List<String> permissions = menuService.getMenuListByUserId(user.getId()).stream().map(Menu::getPerms).collect(Collectors.toList());

        List<String> permissions = new ArrayList<>();
        for (Menu menu : menuService.getMenuListByUserId(user.getId())) {
                permissions.add(menu.getPerms());
                getChildPerms(menu.getChildren(), permissions);
        }
        permissions = permissions.stream().filter(Objects::nonNull).collect(Collectors.toList());
        return new LoginUser(user, permissions);
    }

    public void getChildPerms(List<Menu> childList, List<String> permissions) {
        if(childList != null) {
            for (Menu menu : childList) {
                permissions.add(menu.getPerms());

                //递归
                getChildPerms(menu.getChildren(), permissions);
            }
        }
    }
}
